<?php
/**
 * 后台customer权限下，wax的测肤建议管理
 * Author: lyun
 * Date: 2019/3/20
 * Created by Panxsoft.
 */


namespace App\Http\Controllers\Admin\Customer;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Admin\Customer\Suggest\WaxSkinSuggestStoreRequest;
use App\Models\Admin\CustomerAdmin;
use App\Models\Customer\CustomerRelateWaxSkin;
use App\Models\Customer\Language;
use App\Models\Customer\WaxSkinSuggest;
use App\Services\Utils\Guard;
use App\Services\Utils\Transaction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;

class WaxSkinSuggestController extends ApiController
{
    const ROUTES = [
        'index'   => 'api.admin.customer.wax.skin.suggest.index',
        'store'   => 'api.admin.customer.wax.skin.suggest.store',
        'destroy' => 'api.admin.customer.wax.skin.suggest.destroy',
    ];

    /**
     *  返回客户自定义的wax测肤建议
     * @test
     *
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function index()
    {
        $login_customer_id = Guard::customer()->id;

        $suggest_customer_id = CustomerRelateWaxSkin::hasWaxSkinSuggest($login_customer_id);

        $wax_skin_suggests = $this->getWaxSkinSuggests($suggest_customer_id);

        return $this->response(compact('wax_skin_suggests'));
    }

    /**
     * 返回默认的wax护肤建议
     *
     * @return array|\Illuminate\Http\Response
     */
    public function create()
    {
        $customer_id = CustomerRelateWaxSkin::CUSTOMER_ID_DEFAULT;

        $wax_skin_suggests = $this->getWaxSkinSuggests($customer_id);

        return $this->response(compact('wax_skin_suggests'));
    }

    /**
     *  customer保存自定义的wax测肤建议
     * @test
     *
     * @param WaxSkinSuggestStoreRequest $request
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function store(WaxSkinSuggestStoreRequest $request)
    {
        $this->isSuperAdmin();

        $customer = Guard::customer();

        $this->deleteOldWaxSkinSuggest($customer->id);

        $wax_skin_suggest_data = $this->assembleWaxSkinSuggest($request, $customer->id);

        $stored = Transaction::handle(function() use($wax_skin_suggest_data){
            foreach($wax_skin_suggest_data as $item)
            {
                /** @var CustomerRelateWaxSkin $customer_relate_wax_skin */
                $customer_relate_wax_skin = CustomerRelateWaxSkin::updateOrCreate($item['customer_relate_wax_skin']);
                $wax_skin_suggest_data_by_language = $this->assembleWaxSkinSuggestByCustomerRelate($item['wax_skin_suggest'], $customer_relate_wax_skin->id);
                WaxSkinSuggest::insert($wax_skin_suggest_data_by_language);
            }

            return true;
        });

        return $this->response(compact('stored'));
    }

    /**
     *  @deprecated (废弃了！只用index，store)
     *  customer更新单条wax测肤建议
     *
     * @param Request $request
     * @param $wax_skin_suggest_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function update(Request $request, $wax_skin_suggest_id)
    {
        $this->isSuperAdmin();

        $wax_skin_suggest = WaxSkinSuggest::find($wax_skin_suggest_id);
            $this->checkItemExist($wax_skin_suggest);

        $wax_skin_suggest_data = $this->assembleWaxSkinSuggestData($request);

        $updated = $wax_skin_suggest->update($wax_skin_suggest_data);

        return $this->response(compact('updated'));
    }

    /**
     * customer 删除wax测肤建议
     * @test
     *
     * @param $customer_id
     * @return array|\Illuminate\Http\Response
     * @throws \Exception
     */
    public function destroy($customer_id)
    {
        $this->isSuperAdmin();

        $login_customer_id = Guard::customer()->id;
        $has_suggest = CustomerRelateWaxSkin::checkWaxSkinSuggest($login_customer_id);
            $this->checkIsTrue($has_suggest, trans('admin.no_customer_wax_skin_suggest'));

        $deleted = $this->deleteSuggest($login_customer_id);

        return $this->response(compact('deleted'));
    }

    /**
     * @param $customer_id
     * @throws \Exception
     */
    private function deleteOldWaxSkinSuggest($customer_id)
    {
        if (CustomerRelateWaxSkin::checkWaxSkinSuggest($customer_id)) {
            $this->deleteSuggest($customer_id);
        }
    }

    /**
     * @param $customer_id
     * @return mixed
     * @throws \Exception
     */
    private function deleteSuggest($customer_id)
    {
        $customer_relate_wax_skin_ids = CustomerRelateWaxSkin::where('customer_id', $customer_id)
            ->where('store_id', CustomerRelateWaxSkin::STORE_ID_DEFAULT)
            ->pluck('id')
            ->toArray();

        $deleted = Transaction::handle(function() use($customer_relate_wax_skin_ids){

//            CustomerRelateWaxSkin::destroy($customer_relate_wax_skin_ids); // 不能删除，关联customer_relate_skin_productable表
            WaxSkinSuggest::whereIn('customer_relate_wax_skin_id', $customer_relate_wax_skin_ids)->delete();

            return true;
        });

        return $deleted;
    }

    /**
     * @param $customer_id
     * @param null $language_id
     * @return Collection|\Illuminate\Support\Collection
     */
    public function getWaxSkinSuggests($customer_id, $language_id = null)
    {
        /** @var Collection $wax_skin_suggests */
        $wax_skin_suggests = (new WaxSkinSuggest)->filterLanguageId($language_id)
            ->whereHas('customerRelateWaxSkin', function ($query) use ($customer_id) {
                return $query->where('customer_id', $customer_id)
                    ->where('store_id', CustomerRelateWaxSkin::STORE_ID_DEFAULT);
            })
            ->with('customerRelateWaxSkin')
            ->get();

        $wax_skin_suggests = $this->transformWaxSkinSuggests($wax_skin_suggests);

        return $wax_skin_suggests;
    }

    /**
     * @param Collection $wax_skin_suggests
     * @return Collection|\Illuminate\Support\Collection
     */
    private function transformWaxSkinSuggests(Collection $wax_skin_suggests)
    {
        $languages = array_flip(Language::getLanguageIds());
        $wax_skin_suggests = $wax_skin_suggests->sortBy('language_id')
            ->groupBy('language_id')
            ->map(function($wax_skin_suggest, $key) use($languages){
                return [
                    'language_id'         => $key,
                    'language_name'       => trans('admin.'.$languages[$key]) ?? '',
                    'suggest_by_language' => $wax_skin_suggest->sortBy('customerRelateWaxSkin.level_sort')
                    ->groupBy('customerRelateWaxSkin.item_id')
                    ->map(function($wax_skin_suggest, $key){
                        return [
                            'item_id'   => $key,
                            'item_name' => trans('admin.wax_itemsid_'.$key),
                            'suggest_by_item_id' => $wax_skin_suggest
                        ];
                    })->sortBy('item_id')
                    ->values()
                ];
            })
            ->values();

        return $wax_skin_suggests;
    }

    /**
     * @param Request $request
     * @param $customer_id
     * @return array
     */
    private function assembleWaxSkinSuggest(Request $request, $customer_id)
    {
        $data = $request->wax_skin_suggests;
        $language_ids = array_keys($data);

        $index = 0;
        $suggest_data = [];
        foreach ($data[$language_ids[0]] as $item_id => $level) {
            foreach ($level as $level_sort => $item_suggest)
            {
                $suggest_data[$index]['customer_relate_wax_skin'] = [
                    'customer_id' => $customer_id,
                    'store_id'    => CustomerRelateWaxSkin::STORE_ID_DEFAULT,
                    'item_id'     => $item_id,
                    'level_sort'  => $level_sort,
                ];
                foreach ($language_ids as $language_id) {
                    $suggest_data[$index]['wax_skin_suggest'][] = [
                        'language_id'    => $language_id,
                        'level_name'     => $data[$language_id][$item_id][$level_sort]['level_name'],
                        'level_intro'    => $data[$language_id][$item_id][$level_sort]['level_intro'],
                        'level_experts'  => $data[$language_id][$item_id][$level_sort]['level_experts'],
                        'level_personal' => $data[$language_id][$item_id][$level_sort]['level_personal'],
                        'level_suggest'  => $data[$language_id][$item_id][$level_sort]['level_suggest'],
                    ];
                }
                $index++;
            }
        }

        return $suggest_data;
    }

    /**
     * @param $wax_skin_suggest
     * @param $customer_relate_wax_skin_id
     * @return mixed
     */
    public function assembleWaxSkinSuggestByCustomerRelate($wax_skin_suggest, $customer_relate_wax_skin_id)
    {
        foreach($wax_skin_suggest as &$suggest_item)
        {
            $suggest_item['customer_relate_wax_skin_id'] = $customer_relate_wax_skin_id;
        }

        return $wax_skin_suggest;
    }

    /**
     * @param $request
     * @return array
     */
    public function assembleWaxSkinSuggestData(Request $request)
    {
        return [
            'level_name'     => $request->level_name,
            'level_intro'    => $request->level_intro,
            'level_experts'  => $request->level_experts,
            'level_personal' => $request->level_personal,
            'level_suggest'  => $request->level_suggest
        ];
    }

    /**
     * @throws \Exception
     */
    private function isSuperAdmin()
    {
        // 超管才能操作的
        $this->checkIsTrue(CustomerAdmin::isGuardSuperAdmin(), trans('admin.is_super_man'));
    }
}
